﻿using CommonViews.Configs;
using CommonViews.Messages;
using CommonViews.Models;
using CommunityToolkit.Mvvm.Messaging;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace CommonViews.Impls
{
    /// <summary>
    /// 
    /*
            
            Serilog.Log.Logger = new LoggerConfiguration()
                .WriteTo.Sink(new Impls.LogViewSink()) //这里使用
                .WriteTo.File("LOGS/log.txt")
                .WriteTo.SQLite("LOGS/log.db")
                .CreateLogger();

    Serilog.Log.Information("XX信息"); //在任何位置LOG

    此SINK结果：
    1）LogViewSink.LogItems中增加LOG信息
    2）WeakReferenceMessenger.Default.Send<LogMessage>()

    */
    /// </summary>
    public class LogViewSink : ILogEventSink
    {
        static string[] _levels = new string[6]
        {
            LogViewConfig.Current.LogVerboseTitle,
            LogViewConfig.Current.LogDebugTitle,
            LogViewConfig.Current.LogInformationTitle,
            LogViewConfig.Current.LogWarningTitle,
            LogViewConfig.Current.LogErrorTitle,
            LogViewConfig.Current.LogFatalTitle
        };

        public static ObservableCollection<LogItem> LogItems { get; set; } = new ObservableCollection<LogItem>(); //这必须new，后new是绑定不了的
        public static int LogItemTotalCount { get; set; } = 0;
        public void Emit(LogEvent logEvent)
        {
            LogItem logItem=new LogItem();
            logItem.Id = LogItemTotalCount++;
            logItem.Level = _levels[(int)logEvent.Level];
            logItem.TimeStamp=logEvent.Timestamp.LocalDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
            logItem.Message = $"{logEvent.MessageTemplate.Render(logEvent.Properties)}";

            


            ////注意：用Task.Run不行
            //ThreadPool.QueueUserWorkItem(delegate
            //{
            //    SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
            //    SynchronizationContext.Current!.Post(async pl =>
            //    {
            //        //里面写真正的业务内容
                    
            //    }, null);
            //});


            

            Application.Current.Dispatcher.Invoke(() =>
            {
                //加入LogItems，并限制LogItems大小
                LogItems.Add(logItem);
                if (LogItems.Count > LogViewConfig.Current.LogItemVisibleCount)
                {
                    //删除最前面一个
                    var item = LogItems.First(i => i.Id == LogItemTotalCount - LogViewConfig.Current.LogItemVisibleCount - 1);
                    if ((item != null))
                    {
                        LogItems.Remove(item);
                    }

                }


            });

            //发送消息
            WeakReferenceMessenger.Default.Send<LogMessage>(new LogMessage(logItem));
        }
    }
}
